<template>
  <!-- 加工退料编辑页 -->
  <div class="e-form">
    <div class="tabs" v-if="Object.keys(basicFormData).length != 0">
      <el-tabs tab-position="left" v-model="tabsName" @tab-click="onChangeTab">
        <!-- 基本信息 -->
        <el-tab-pane
          label="基本信息"
          name="baseInfo"
          :disabled="clickTabFlag"
        ></el-tab-pane>
        <el-tab-pane
          label="退库明细"
          name="planDetail"
          :disabled="clickTabFlag"
        ></el-tab-pane>

        <el-tab-pane
          label="附件信息"
          name="accessory"
          :disabled="clickTabFlag"
        ></el-tab-pane>
        <el-tab-pane
          label="审核历史"
          name="auditHistory"
          :disabled="clickTabFlag"
        ></el-tab-pane>

        <div>
          <!-- 基本信息 -->
          <div id="baseInfoCon" class="con">
            <div class="e-form">
              <BillTop title="加工退料编辑" @cancel="cancel"></BillTop>
              <div class="tabs">
                <div class="tabs-title" id="baseInfo">基本信息</div>
                <div style="width: 100%" class="form" >
                  <el-form :model="basicFormData" label-width="150px"  ref="ruleForm"
                    :rules="rules"
                    class="demo-ruleForm">
                    <el-row>
                      <el-col :span="12">
                        <el-form-item label="业务类型：" prop="businessType">
                          {{['','分包合同','销售合同','事实合同'][basicFormData.businessType]}}
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">

                            <el-form-item label="合同：">
                          <el-input
                            v-model="basicFormData.contractBillName"
                          >
                          </el-input>
                             <el-button  type="primary" style="background: #2e61d7;margin-left:5px" @click="ExamineContract">查看</el-button>
                        </el-form-item>

                      </el-col>
                    </el-row>
                    <el-row>
                      <el-col :span="12">
                        <el-form-item label="领料单位：">
                          <el-input
                            v-model="basicFormData.pickingUnitName"
                          >
                          </el-input>
                            <el-button  type="primary" style="background: #2e61d7;margin-left:5px" @click="selectProcessIssue">选择加工发料</el-button>
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item label="领料人员：">
                          {{basicFormData.pickingPersonnelName}}
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row>
                      <el-col :span="12">
                        <el-form-item label="退料编号：">
                          {{basicFormData.billNo}}

                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item label="退料日期：" prop="returnDate">
                          <el-date-picker
                            v-model="basicFormData.returnDate"
                            type="date"
                            placeholder="选择日期"
                            value-format="yyyy-MM-dd"
                            :clearable="false"
                          >
                          </el-date-picker>
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row>
                      <el-col :span="12">
                           <el-form-item label="收料类型：" prop="receiptType">
                                    <el-radio-group v-model="basicFormData.receiptType">
                                      <el-radio :label="0">普通加工</el-radio>
                                      <el-radio :label="1">砼加工</el-radio>
                                    </el-radio-group>
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item label="所属机构：">
                          {{basicFormData.orgName}}

                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row>
                      <el-col :span="12">
                        <el-form-item label="发料人员：">
                          {{basicFormData.issuingPersonnelName}}
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item label="加工单位：">
                          {{basicFormData.processingUnitName}}
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row>
                      <el-col :span="12">
                        <el-form-item label="加工合同：">
                            <el-input
                            v-model="basicFormData.processingContractNumber"
                          >
                          </el-input>
                            <el-button  type="primary" style="background: #2e61d7;margin-left:5px" @click="ExamineprocessingContract">查看</el-button>
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item label="退料数量：">
                          {{basicFormData.returnQuantity}}
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row>
                      <el-form-item label="状态：">
                        {{
                          ["草稿", "审核中", "已审核", "已关闭", "已作废"][
                            basicFormData.state
                          ]
                        }}
                      </el-form-item>
                    </el-row>
                    <el-row>
                      <el-form-item label="备注：">
                        <el-input
                          type="textarea"
                          :rows="2"
                          placeholder="请输入内容"
                          v-model="basicFormData.remarks"
                        >
                        </el-input>
                      </el-form-item>
                    </el-row>
                  </el-form>
                </div>
              </div>
            </div>

          </div>

           <!-- 退库明细 -->
          <div id="planDetailCon" class="con">
            <div class="tabs-title" id="planDetail">退库明细</div>
            <el-tabs
              :class="'childTab ' + childTabClass"
              tab-position="left"
              v-model="tabsNameChild"
              @tab-click="onChangeTab"
            >
              <el-tab-pane
                label="成品物资"
                name="materialDetails"
                :disabled="clickTabFlag"
              ></el-tab-pane>
              <el-tab-pane
                label="原物资"
                name="technicalParameter"
                :disabled="clickTabFlag"
              ></el-tab-pane>
              <div>
                <div id="planDetailCon">
                  <div class="tabs-title" id="materialDetails">
                    成品物资
                  </div>
                  <div class="e-table">
                  <!-- 成品物资 -->

                      <div class="errorMsg" v-if="errorMsg.length>0">
                          <span v-for="item,index in errorMsg" :key="index">
                              {{item}}
                          </span>
                      </div>
                    <el-table
                      class="table"
                      :data="FinishedGoodsData"
                      border
                      style="width: 100%"
                      @cell-mouse-enter="cellMouseEnter"
                      @cell-mouse-leave="cellMouseLeave"
                      :cell-class-name="cellClsNm"
                      :header-cell-style="{ textAlign: 'center' }"
                      :cell-style="{ textAlign: 'center' }"
                       :tree-props="{
                        children: 'children',
                        hasChildren: 'hasChildren',
                        }"
                        row-key="uuid"
                        :max-height="$store.state.tableHeight"
                         ref="table"
                v-sortTable="{ 'tableData': FinishedGoodsData, '_this': this, 'ref': 'table' }"
                    >
                     <el-table-column  fixed type="index" label="序号" width="80" align="center">
                     </el-table-column>
                      <el-table-column
                        prop="materialClassName"
                        label="类别"
                        min-width="200"
                      >
                      </el-table-column>
                      <el-table-column
                        prop="materialName"
                        label="物资名称"
                        min-width="150"
                      >
                      </el-table-column>
                      <el-table-column
                        prop="spec"
                        label="规格"
                        width="150"
                      >
                      </el-table-column>
                      <el-table-column
                        prop="texture"
                        label="材质"
                        width="150"
                      >
                      </el-table-column>
                      <el-table-column
                        prop="unit"
                        label="单位"
                        width="150"
                      >
                      </el-table-column>
                      <el-table-column
                        prop="subItemName"
                        label="分部分项"
                        width="150"
                        v-if="basicFormData.businessType ===1"
                      >
                      </el-table-column>
                      <el-table-column
                        prop="issuingWarehouseName"
                        label="发料仓库"
                        width="150"
                      >
                      </el-table-column>
                          <el-table-column
                        prop="pickingWarehouseName"
                        label="领料仓库"
                        width="150"
                      >

                      </el-table-column>
                          <el-table-column
                        prop="returnQuantity"
                        label="退库数量"
                        width="150"
                      >
                      </el-table-column>

                    </el-table>

                  </div>
                </div>
              <!--  原物资   -->
                <div id="planDetailCon">
                  <div class="tabs-title" id="technicalParameter">原物资</div>
                  <div class="e-table">
                    <el-table
                      class="table"
                      :data="materialsTableData"
                      border
                      style="width: 100%"
                      @cell-mouse-enter="cellMouseEnter"
                      @cell-mouse-leave="cellMouseLeave"
                      :cell-class-name="cellClsNm"
                      :header-cell-style="{ textAlign: 'center' }"
                      :cell-style="{ textAlign: 'center' }"
                      :tree-props="{
                            children: 'children',
                            hasChildren: 'hasChildren',
                             }"
                       row-key="uuid"
                       :max-height="$store.state.tableHeight"
                       ref="table"
                v-sortTable="{ 'tableData': materialsTableData, '_this': this, 'ref': 'table' }"
                    >
                     <el-table-column  fixed type="index" label="序号" width="80" align="center">
                     </el-table-column>
                      <el-table-column prop="materialClassName" label="类别" min-width="150">
                      </el-table-column>
                      <el-table-column
                        prop="materialName"
                        label="物资名称"
                        min-width="150"
                      >
                      </el-table-column>
                      <el-table-column prop="spec" label="规格" width="100">
                      </el-table-column>
                      <el-table-column prop="texture" label="材质" width="100">
                      </el-table-column>
                      <el-table-column prop="unit" label="单位" width="100">
                      </el-table-column>
                      <el-table-column prop="issuingWarehouseName" label="发料仓库" width="100">
                      </el-table-column>
                      <el-table-column prop="pickingWarehouseName" label="领料仓库" width="100">
                      </el-table-column>
                      <el-table-column prop="returnQuantity" label="退料数量" width="100">
                      </el-table-column>
                    </el-table>

                  </div>
                </div>
              </div>
            </el-tabs>
          </div>

          <!-- 附件信息 -->
          <div id="accessoryCon" class="con">
            <div class="tabs-title" id="accessory">附件信息</div>
            <attach-comp
              :relationId="attachId"
              bucketName="material"
              v-if="objFlag.flag5"
            />
            <div class="seize-a-seat" v-else>
              <i class="el-icon-loading"></i>
            </div>
          </div>
          <!-- 审核历史 -->
          <div id="auditHistoryCon" class="con">
                        <div class="tabs-title" id="auditHistory">审核历史</div>
                        <div class="e-table">
                            <ComAuditHistoryIndex
                                :tableData.sync="auditHistoryTable"
                                @getAuditHistory="getAuditHistory"
                                ref="AuditHistoryRef"
                            />
                        </div>
                    </div>
        </div>
      </el-tabs>
    </div>
    <div id="seat" :style="{ height: seatHeight + 'px' }"></div>
    <div class="buttons">
       <span class="tip"
        ><span style="color: red; margin-right: 0">*</span>为必填项</span
      >
        <el-button
          type="primary"
          style="background: #2e61d7"
          v-debounce
          v-if="basicFormData.state === '1'"
          >打印</el-button
      >
        <ComExaButtons
                v-if="basicFormData.state != 5"
                :auditState="auditState"
                :state="basicFormData.state"
                 :founderId="founderId"
                @exas="exas"
            />

     <!-- <el-button type="primary" style="background: #2e61d7" @click="save('basicFormData')"
       v-debounce
        >保存</el-button
      >
      <el-button type="primary" style="background: #2e61d7" @click="submit('basicFormData')"
       v-debounce
        >保存并提交</el-button
      >
       <el-button
            type="primary"
            style="background: #2e61d7"
            v-debounce
            v-if="basicFormData.state === '1'"
            @click="undoAudit"
            >撤回</el-button
          >
      <el-button
        type="primary"
        class="btn-delete"
        v-debounce
        v-if="basicFormData.state === '1'"
        @click="nullify()"
        >作废</el-button
          > -->
      <el-button type="danger" size="small" @click="ctDelete" v-if="basicFormData.state === '0'">删除</el-button>
      <el-button @click="cancel()">关闭</el-button>
    </div>
  </div>
</template>

<script>
import '@/utils/jquery.scrollTo.min'
import { mapMutations } from 'vuex'
import AttachComp from '@/components/common/attachIndex'
import Api from '@/api/materials/processReturn.js'
import CommonApi from '@/api/materials/common.js'
import {  getUuid, selectDataClient, openAppClient } from '@/utils/common'
import ComAuditHistoryIndex from '@/pages/materialsmanagement/components/auditHistory/auditHistoryIndex'
export default {
    data () {
        return {
            tabsName: 'baseInfo',
            userName: '',
            clickId: 'baseInfo',
            tabsNameChild: '',
            childTabClass: '',
            form: {
                name: '',
                region: '',
                date1: '',
                date2: '',
                delivery: false,
                type: [],
                resource: '',
                desc: '',
            },
            isBatch: [
                {
                    flag: false,
                    batch: '进入批量管理'
                },
                {
                    flag: false,
                    batch: '进入批量管理'
                }
            ],
            currentRow: {},
            auditState: {}, //按钮状态
            errorList: [], //控制导航栏感叹号的显示
            errorMsg: [], //计划明细错误显示
            isErrorMsg: true, //是否提醒错误信息
            FinishedGoodsData: [], //成品物资
            materialsTableData: [], //原物资
            auditHistoryTable: [], //审核历史
            planSelect: [],
            value: '',
            textarea: '',
            formData: {},
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            //基本信息表单数据
            basicFormData: {
                'billId': '',
                'billNo': '',
                'businessType': null,
                'contractBillId': '',
                'contractBillName': '',
                'contractBillNo': '',
                'currentTotalReturnQuantity': 0,
                'founderId': '',
                'founderName': '',
                'gmtCreate': '',
                'gmtModified': '',
                'issuingPersonnelId': '',
                'issuingPersonnelName': '',
                'nullifyCreated': '',
                'nullifyCreator': '',
                'nullifyCreatorId': '',
                'nullifyDescription': '',
                'nullifyReason': '',
                'orgId': '',
                'orgName': '',
                'pickingPersonnelId': '',
                'pickingPersonnelName': '',
                'pickingUnitId': '',
                'pickingUnitName': '',
                'previousTotalReturnQuantity': 0,
                'processingContractId': '',
                'processingContractNumber': '',
                'processingIssueBillId': '',
                'processingUnitId': '',
                'processingUnitName': '',
                'receiptType': null,
                'remarks': '',
                'returnDate': '',
                'returnQuantity': 0,
                'state': '',
                'workId': ''
            },
            objFlag: {
                flag5: false,
            },
            rules: {
                businessType: [
                    { required: true, message: '请选择业务类型', trigger: 'change' },
                ],
                returnDate: [
                    { required: true, message: '请选择退料日期', trigger: 'change' },
                ],
                receiptType: [
                    { required: true, message: '请选择收料类型', trigger: 'change' },
                ],

            },
            options: [
                {
                    value: 1,
                    key: '分包合同',
                },
                {
                    value: 2,
                    key: '销售合同',
                },
                {
                    value: 3,
                    key: '事实合同',
                },
            ],
            orgId: '', //机构id
            orgName: '', //机构名称
            billid: '',
            isSkip: false, //是否跳转
            show: true, //申报机构子列表
            showTwo: false,
            dtlIds: '', //
            billIdArr: [],
            OrgAllData: [],
            data: [],
            processIssueId: '',
            UidArr: [],
            auditParams: {
                billId: this.$route.query.billid, //单据Id  ***
                billType: '1013', //单据编码  ***
                dtls: [], //审核中字段值变更历史
                freeNextUnitIndex: 0, //下一步审核步骤
                freeNextUser: '', //下一步审核人ID
                isPass: true, //审核是否通过
                isShareInAudit: true, //是否共享审核节点
                opinion: '', //审核意见   ***
                orgId: JSON.parse(localStorage.getItem('vuex')).userInfo.orgInfo.orgId, //单据机构Id
                orgName: JSON.parse(localStorage.getItem('vuex')).userInfo.orgInfo.orgName, //单据机构名称
                userId: localStorage.getItem('userId'), //审核人Id    ***
                workId: '', //流程Id
            },
            nullifyParams: { //作废
                'billId': this.$route.query.billid,
                'billType': 1013,
                'nullifyCreated': '',
                'nullifyCreator': '',
                'nullifyCreatorId': '',
                'nullifyDescription': '',
                'nullifyReason': ''
            },

        }
    },
    computed: {
        judgeRoute () {
            if (this.$route.path.includes('Add')) {
                return false
            }
            return true
        },
        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 72 - this.lastConHeight
        },
        attachId () {
            return this.billid
        },
    },
    components: {
        AttachComp,
        ComAuditHistoryIndex,
    },
    watch: {
        //给错误标签加上提醒
        errorList: newData => {
            const tabs = document.querySelectorAll('.el-tabs__item')
            tabs.forEach(DOM => {
                const { childNodes } = DOM
                if (childNodes.length > 1) {
                    DOM.removeChild(childNodes[1])
                }
            })
            newData.forEach(item => {
                const itemDom = document.querySelector(`#tab-${item}`)
                var element = document.createElement('i')
                element.className = 'el-icon-warning-outline warning'
                itemDom.appendChild(element)
            })
        },
    },

    created () {
        let data = JSON.parse(localStorage.getItem('vuex'))
        this.orgId = data.userInfo.orgInfo.orgId
        this.orgName = data.userInfo.orgInfo.orgName
        this.founderId = localStorage.getItem('userId')
        this.userId = localStorage.getItem('userId')
        this.billid = this.$route.query.billid
        this.getBasicData() //进入页面就获取基本信息数据
        this.getMasterPlan()
        this.getRawMaterialsList()
        this.getAttach()
        this.getAuditHistory()
        this.getCurrentUnitInfo()

    },
    mounted () {
    // 获取最后一个内容区域的高度，计算底部空白
        this.getLastConHeight()

        // 保存所有tabName
        const arr = [
            'baseInfo',
            ['planDetail', 'materialDetails', 'technicalParameter'],
            'accessory',
            'auditHistory',
        ]
        this.tabArr = arr //标星星
        let $idsTop = []
        window.addEventListener('scroll', () => {
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            //当点击的tab有子tab时做滚动逻辑
            if (this.clickTabFlag && arr.find(x => x === this.clickId)) {
                this.childTabClass = '' //无子tab时清空tab的类名
                return
            }

            if (!$idsTop[$idsTop.length - 1]) {
                $idsTop = arr.map(item => {
                    let itemTop
                    let arr
                    if (item instanceof Array) {
                        const prevHeight = document.getElementById(item[0]).offsetHeight //因这里一个选项有两个表格，需获取前一个表格的高度进行计算
                        arr = item.map((x, i) => {
                            if (i === 0) {
                                return document.getElementById(x).offsetTop
                            } else {
                                return (
                                    document.getElementById(x).offsetTop +
                  prevHeight +
                  document.getElementById(item[0]).offsetTop
                                )
                            }
                        })
                        return arr
                    } else {
                        itemTop = document.getElementById(item).offsetTop
                        return itemTop
                    }
                })
            }
            const scrollTop =
        document.documentElement.scrollTop || document.body.scrollTop
            // 倒序查找
            let curLocal = 0
            let curLocalChild = 1
            for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                if ($idsTop[i] instanceof Array) {
                    let item = $idsTop[i]
                    for (let lenth = item.length, j = lenth - 1; j >= 1; j--) {
                        let itemChild = $idsTop[i][j]
                        if (scrollTop + 1 >= itemChild) {
                            curLocalChild = j
                            break
                        }
                    }
                    if (scrollTop + 1 >= item[0]) {
                        curLocal = i
                        break
                    }
                } else {
                    let item = $idsTop[i]
                    if (scrollTop + 1 >= item) {
                        curLocal = i
                        break
                    }
                }
            }
            // 设置对应tabName
            if (arr[curLocal] instanceof Array) {
                this.tabsName = arr[curLocal][0]
                this.tabsNameChild = arr[curLocal][curLocalChild]
            } else {
                this.tabsName = arr[curLocal]
            }
            //动态改变二级选项卡类名
            arr.forEach((item, index) => {
                if (item instanceof Array) {
                    let tabNavHeight = document.querySelector('.childTab .el-tabs__nav')
                        ? document.querySelector('.childTab .el-tabs__nav').offsetHeight
                        : 0
                    if (scrollTop + 1 >= $idsTop[index + 1] - tabNavHeight) {
                        this.childTabClass = 'childTab2'
                    } else if (scrollTop <= $idsTop[index][1]) {
                        this.childTabClass = ''
                    } else {
                        this.childTabClass = 'childTab1'
                    }
                }
            })
        })

        this.screenWidth = document.documentElement.clientWidth - this.topHeight
        this.screenHeight = document.documentElement.clientHeight - this.topHeight
        window.addEventListener('resize', () => {
            this.screenWidth = document.documentElement.clientWidth - this.topHeight
            this.screenHeight = document.documentElement.clientHeight - this.topHeight
            $idsTop = arr.map(item => {
                let itemTop
                let arr
                if (item instanceof Array) {
                    const prevHeight = document.getElementById(item[0]).offsetHeight //因这里一个选项有两个表格，需获取前一个表格的高度进行计算
                    arr = item.map((x, i) => {
                        if (i === 0) {
                            return document.getElementById(x).offsetTop
                        } else {
                            return (
                                document.getElementById(x).offsetTop +
                prevHeight +
                document.getElementById(item[0]).offsetTop
                            )
                        }
                    })
                    return arr
                } else {
                    itemTop = document.getElementById(item).offsetTop
                    return itemTop
                }
            })
        })
        this.scorllDtl()
    },
    methods: {
        ...mapMutations(['setSelectedInfo', 'setAuditParams']),
        // 获取按钮状态
        getCurrentUnitInfo () {
            CommonApi
                .getCurrentUnitInfo({
                    billId: this.$route.query.billid,
                    billType: 1013,
                    freeNextUnitIndex: 0,
                    freeNextUser: '',
                    isPass: true,
                    isShareInAudit: true,
                    opinion: ''
                })
                .then(res => {
                    this.auditState = res
                })
        },
        // 按钮组件触发事件
        exas (data) {
            switch (data) {
            case 'audit':
                this.audit() //审核
                break
            case 'undoAudit':
                this.undoAudit() //撤回
                break
            case 'submitCommit':
                this.submit() //提交
                break
            case 'submit':
                this.save() //保存
                break
            case 'nullify':
                this.nullify() //作废
                break
            case 'deleteData':
                this.ctDelete() //删除
                break
            default:
                break
            }
        },
        //计算退库数量
        totalreturnQuantity () {
            let num = 0
            this.FinishedGoodsData.forEach(a=>{
                a.children.forEach(b=>{
                    num += Number(b.returnQuantity)
                })
            })
            this.basicFormData.returnQuantity = num
        },
        //作废
        nullify () {
            this.setAuditParams(this.nullifyParams)
            openAppClient('/nullifyDialog', '单据作废原因', () => {
                const auditParams = JSON.parse(localStorage.vuex).auditParams
                CommonApi.nullify(auditParams).then(() => {
                    this.clientPop('suc', '作废成功', this.cancel, null, this.cancel)
                })
            })
        },
        //撤回
        undoAudit () {
            const params2 = {
                billId: this.billid, //单据Id  ***
                billType: '1013', //单据编码  ***
                dtls: [], //审核中字段值变更历史
                freeNextUnitIndex: 0, //下一步审核步骤
                freeNextUser: '', //下一步审核人ID
                isPass: true, //审核是否通过
                isShareInAudit: true, //是否共享审核节点
                opinion: '', //审核意见   ***
                orgId: '', //单据机构Id
                orgName: '', //单据机构名称
                userId: this.userId, //审核人Id    ***
                workId: '', //流程Id
            }
            CommonApi.undoAudit(params2).then(() => {
                this.clientPop('suc', '撤回成功！', this.cancel, null, this.cancel)
            })
        },

        //跳转到明细
        scorllDtl () {
            if(this.$route.query.name) {
                setTimeout(() => {
                    //因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                    let obj = {
                        name: this.$route.query.name
                    }
                    this.tabsName = this.$route.query.name
                    this.onChangeTab(obj)
                }, 200)
            }
        },
        //查看合同
        ExamineContract () {
            if(this.basicFormData.businessType === 1) {
                let id = this.basicFormData.contractBillId
                openAppClient(`/contractDefinitionShow?billid=${id}&isview=${true}`, '查看源单', function () {
                })

            }else if(this.basicFormData.businessType === 2) {
                let id = this.basicFormData.contractBillId
                openAppClient(`/ctMaterialSalesSigningShow?billid=${id}&isview=${true}`, '查看源单', function () {
                })
            }
        },
        //查看加工合同
        ExamineprocessingContract () {
            let id = this.basicFormData.processingContractId
            openAppClient(`/processingContractApplyShow?billid=${id}&isview=${true}`, '查看源单', function () {
            })
        },
        //选择加工发料
        selectProcessIssue () {

            let ids = []
            selectDataClient({
                SelectServiceToken: '/material/processingIssue/listBaseInfoByOrgIdForSelect',
                IsSingleMode: true, // 是否单选 true 单选 false 多选
                SelectedIDs: ids, // 已选中id(注意：是上一次已选中的id，不是要传的参数，如果第一次选，则传[])
                InitParamsStr: JSON.stringify(this.orgId),
                Title: '选择加工发料单'
            })
                .then(val=>{
                    this.setSelectedInfo(val)

                    //         openAppClient('/showSelectedData', '选择结果', function () {
                    //             // alert('关闭后回调')
                    //         })
                    // let val = [{ 'billId': '1564179475059109889', 'billNo': 'SRBGEHGSL204JGFL20220829001', 'businessType': 1, 'contractBillId': '1563461086422429698', 'contractBillNo': 'SRBGEHGSL204FBHT007', 'contractBillName': '1233214142', 'issuingPersonnelId': '', 'issuingPersonnelName': '李秀林', 'pickingPersonnelId': '', 'pickingPersonnelName': '', 'pickingUnitId': 'a9962ed808ba-a68c-1b4a-f8c7-713b7a13', 'pickingUnitName': '文志', 'processingContractId': '1562997198014836737', 'processingContractName': null, 'processingUnitId': '1562821994512838658', 'processingUnitName': 'LY测试专用供应单位', 'receiptType': 0 }]
                    val.forEach(item=>{
                        this.basicFormData.businessType = item.businessType  //业务类型
                        this.basicFormData.contractBillId = item.contractBillId  //合同id
                        this.basicFormData.contractBillName = item.contractBillName //合同编号
                        this.basicFormData.pickingUnitId = item.pickingUnitId //领料单位id
                        this.basicFormData.pickingUnitName = item.pickingUnitName //领料单位名称
                        this.basicFormData.pickingPersonnelId = item.pickingPersonnelId //领料人员id
                        this.basicFormData.pickingPersonnelName = item.pickingPersonnelName//领料人名称
                        this.basicFormData.receiptType = item.receiptType //收料类型
                        this.basicFormData.issuingPersonnelId = item.issuingPersonnelId//发料人id
                        this.basicFormData.issuingPersonnelName = item.issuingPersonnelName//发料人名称
                        this.basicFormData.processingUnitId = item.processingUnitId//加工单位id
                        this.basicFormData.processingIssueBillId = item.billId  //加工发料id
                        this.basicFormData.processingUnitName = item.processingUnitName//加工单位名称
                        this.basicFormData.processingContractId = item.processingContractId
                        this.basicFormData.processingContractNumber = item.processingContractName
                        this.getFinishedGoodsById(item.billId)
                        this.getRawMaterialsById(item.billId)
                    })
                })

        },
        //根据加工发料id获取成品物资明细
        getFinishedGoodsById (id) {
            this.$Ajax
                .httpGet({
                    url: '/material/processingIssue/getFinishedGoodsByIdForSelect',
                    params: {
                        id: id,
                    },
                })
                .then(res=>{
                    const mapObj = {}
                    let arr = []
                    this.Uids = res.length
                    this.getId()
                    setTimeout(()=>{
                        res.forEach((e, index) => {
                            const children = []
                            e.materialClassNameArr = e.materialClassName.split('/')
                            e.materialClassIdArr = e.materialClassId.split('/')
                            // TODO: 统计小计
                            let obj
                            const topClassId = e.materialClassIdArr.splice(0, 1).toString()
                            const topClassName = e.materialClassNameArr.splice(0, 1).toString()
                            if (!mapObj[topClassId]) {
                                obj = {
                                    topClassId,
                                    topClassName,
                                    customId: topClassId,
                                    materialClassId: topClassId,
                                    materialClassName: topClassName,
                                    uuid: getUuid(),
                                    totalAmount: '',
                                    totalQuantity: '',
                                }
                                //这里需要改成push多个对象   还没改
                                arr.push(obj)

                                mapObj[topClassId] = obj
                            } else {
                                obj = mapObj[topClassId]
                            }

                            // 物资名称
                            children.push({
                                uuid: getUuid(),
                                customId: getUuid(),
                                'billId': this.billid, //加工退料id
                                'changeType': 1, //
                                'dtlId': this.UidArr[index], //加工退料—成品物资明细id
                                'issuingWarehouseId': e.issuingWarehouseId, //发料仓库id
                                'issuingWarehouseName': e.issuingWarehouseName, //发料仓库名称
                                'materialClassId': e.materialClassIdArr.join('/'), //物资类别id
                                'materialClassName': e.materialClassNameArr.join('/'), //物资类别名称
                                'materialId': e.materialId, //物资id
                                'materialName': e.materialName, ///物资名称
                                'pickingWarehouseId': e.pickingWarehouseId, //领料仓库id
                                'pickingWarehouseName': e.pickingWarehouseName, //领料仓库名称
                                'returnQuantity': e.collectedQuantity, //退库数量
                                'spec': e.spec, //规格型号
                                'subItemId': e.subItemId, //分部分项id
                                'subItemName': e.subItemName, //分部分项名称
                                'texture': e.texture, //材质
                                'unit': e.unit//计量单位
                            })
                            obj.children = !obj.children
                                ? children
                                : obj.children.concat(children)
                            // 统计小计
                            const count = obj.children.reduce(
                                (prev, c) => (prev += c.returnQuantity || 0),
                                0
                            )
                            obj.materialName = `小计： ${count.toFixed(4)}`
                            obj.children = this.uniqueArray(obj.children, 'customId')
                        })
                        this.FinishedGoodsData = arr
                        this.totalreturnQuantity()
                    }, 500)
                })
        },
        //根据加工发料id获取原物资明细
        getRawMaterialsById (id) {
            this.$Ajax
                .httpGet({
                    url: '/material/processingIssue/getRawMaterialsByIdForSelect',
                    params: {
                        id: id,
                    },
                })
                .then(val=>{
                    const mapObj = {}
                    let arr = []
                    this.Uids = val.length
                    this.getId()
                    setTimeout(()=>{
                        val.forEach((e, index) => {
                            const children = []
                            e.materialClassNameArr = e.materialClassName.split('/')
                            e.materialClassIdArr = e.materialClassId.split('/')
                            // TODO: 统计小计
                            let obj
                            const topClassId = e.materialClassIdArr.splice(0, 1).toString()
                            const topClassName = e.materialClassNameArr.splice(0, 1).toString()

                            if (!mapObj[topClassId]) {
                                obj = {
                                    topClassId,
                                    topClassName,
                                    customId: topClassId,
                                    materialClassId: topClassId,
                                    materialClassName: topClassName,
                                    uuid: getUuid(),
                                    totalAmount: '',
                                    totalQuantity: '',
                                }
                                //这里需要改成push多个对象   还没改
                                arr.push(obj)

                                mapObj[topClassId] = obj
                            } else {
                                obj = mapObj[topClassId]
                            }

                            // 物资名称
                            children.push({
                                uuid: getUuid(),
                                customId: getUuid(),
                                billId: this.billid, //	加工退料id		false
                                changeType: 1, //		变更类型		false
                                dtlId: '', //		原物资明细id		false
                                finishedGoodsDtlId: this.UidArr[index], //		成品物资id		false
                                issuingWarehouseId: e.issuingWarehouseId, //		发料仓库id		false
                                issuingWarehouseName: e.issuingWarehouseName, //		发料仓库名称		false
                                materialClassId: e.materialClassIdArr.join('/'), //		物资类别id(1级类别id/2级类别id/..)		false
                                materialClassName: e.materialClassNameArr.join('/'), //		物资类别名称(1级类别名称/2级类别名称/..)		false
                                materialId: e.materialId, //		物资id		false
                                materialName: e.materialName, //		物资名称		false
                                pickingWarehouseId: e.pickingWarehouseId, //		领料仓库id		false
                                pickingWarehouseName: e.pickingWarehouseName, //		领料仓库名称		false
                                returnQuantity: e.collectedQuantity, //		退库数量		false
                                spec: e.spec, //		规格型号		false
                                texture: e.texture, //		材质		false
                                unit: e.unit, //		计量单位

                            })
                            obj.children = !obj.children
                                ? children
                                : obj.children.concat(children)
                            // 统计小计
                            const count = obj.children.reduce(
                                (prev, c) => (prev += c.returnQuantity || 0),
                                0
                            )
                            obj.materialName = `小计： ${count.toFixed(4)}`
                            obj.children = this.uniqueArray(obj.children, 'customId')
                        })
                        this.materialsTableData = arr

                    }, 500)
                })
        },
        // //保存
        // save (formName) {
        //     this.$refs[formName].validate(valid => {
        //         if (valid) {
        //             //基础信息
        //             const p1 =  Api.EditProcessReturn(this.basicFormData)
        //             //成品物资
        //             const p2 = Api.EditFinishedGoodsList(this.FinishedGoodsData)
        //             //保存原物资
        //             const p3 = Api.EditRawMaterialsList(this.materialsTableData)
        //             Promise.all([p1, p2, p3]) .then(() => {
        //                 this.clientPop('suc', '保存成功！', ()=>{
        //                     this.getBasicData()
        //                     this.getMasterPlan()
        //                     this.getRawMaterialsList()
        //                 }
        //                 )
        //             })
        //         } else {
        //             return false
        //         }
        //     })
        // },
        // //提交
        // submit (formName) {
        //     this.$refs[formName].validate(valid => {
        //         if (valid) {
        //             const params = {
        //                 billId: this.billid, //单据Id  ***
        //                 billType: '1013', //单据编码  ***
        //                 dtls: [], //审核中字段值变更历史
        //                 freeNextUnitIndex: 0, //下一步审核步骤
        //                 freeNextUser: '', //下一步审核人ID
        //                 isPass: true, //审核是否通过
        //                 isShareInAudit: true, //是否共享审核节点
        //                 opinion: '', //审核意见   ***
        //                 orgId: this.orgId, //单据机构Id
        //                 orgName: this.orgName, //单据机构名称
        //                 userId: this.userId, //审核人Id    ***
        //                 workId: '', //流程Id
        //             }
        //             const p1 =  Api.EditProcessReturn(this.basicFormData)
        //             //成品物资
        //             const p2 = Api.EditFinishedGoodsList(this.FinishedGoodsData)
        //             //保存原物资
        //             const p3 = Api.EditRawMaterialsList(this.materialsTableData)
        //             const p4 = CommonApi.AuditCommit(params)
        //             Promise.all([p1, p2, p3, p4]).then(() => {
        //                 this.clientPop('suc', '保存并提交成功！', this.cancel)
        //             })
        //         } else {
        //             return false
        //         }
        //     })
        // },
        //保存
        save () {
            this.errorList = []
            Promise.all([this.updateBaseInfo(), this.updateBudgetDtl()])
                .then(() => {
                    this.clientPop('suc', '保存成功', this.$router.go(0))
                })
                .catch(() => {
                    this.scorllError()
                })
        },
        //保存并提交
        submit () {
            this.errorList = []
            Promise.all([this.updateBaseInfo(), this.updateBudgetDtl()])
                .then(() => {
                    CommonApi.AuditCommit(this.auditParams).then(() => {
                        this.clientPop('suc', '保存并提交成功', this.cancel, null, this.cancel)
                    })
                })
                .catch(() => {
                    this.scorllError()
                })

        },
        //更新基本信息
        updateBaseInfo () {
            return new Promise((resolve, reject) => {
                this.$refs.ruleForm.validate(valid => {
                    if (valid) {
                        Api.EditProcessReturn(this.basicFormData)
                            .then(() => {
                                this.getBasicData() //更新基本信息
                                resolve()
                            })
                            .catch(err => {
                                this.setError('baseInfo')
                                reject(err)
                            })
                    } else {
                        this.setError('baseInfo')
                        this.scorllError()
                        return false
                    }
                })
            })
        },
        //更新计划明细
        updateBudgetDtl () {
            return new Promise((resolve, reject) => {
                this.verifyTable()
                    .then(() => {
                        const p1 = Api.EditFinishedGoodsList(this.FinishedGoodsData)
                        const p2 =  Api.EditRawMaterialsList(this.materialsTableData)
                        Promise.all([p1, p2])
                            .then(() => {
                                this.getMasterPlan() //更新明细
                                resolve()
                            })
                            .catch(err => {
                                this.setError('')
                                reject(err)
                            })
                    })
                    .catch(err => {
                        this.setError('')
                        reject(err)
                    })
            })
        },
        //明细非空验证
        verifyTable () {
            return new Promise((resolve, reject) => {
                this.errorMsg = []
                // if(this.materialsTableData.length === 0) {
                //     let str = '退库明细不能为空！'
                //     this.errorMsg.push(str)
                // }
                // if(this.FinishedGoodsData.length === 0) {
                //     let str = '退库明细不能为空！'
                //     this.errorMsg.push(str)
                // }
                // else
                if (this.FinishedGoodsData.length > 0) {
                    this.FinishedGoodsData.forEach(v => {
                        v.children.forEach((item, index) => {
                            if (item.changeType !== -1) {
                                if (item.authorizedQuantity === '' || item.authorizedQuantity === null) {
                                    let str = `请填写第 ${index + 1} 行的核准数量`
                                    this.errorMsg.push(str)
                                }

                            }
                        })
                    })
                }

                if (this.errorMsg.length > 0) {
                    this.isErrorMsg = true
                    reject()
                } else {
                    this.isErrorMsg = false
                    resolve()
                }
            })
        },
        setError (name) {
            if (!this.errorList.find(x => x === name)) {
                this.errorList.push(name)
            }
        },
        //跳转到第一个错误标签
        scorllError () {
            let num = this.tabArr.length
            this.errorList.forEach(item => {
                let index = this.tabArr.findIndex(x => x === item)
                num = index < num ? index : num
            })
            const obj = { name: this.tabArr[num] }
            this.tabsName = this.tabArr[num]
            this.onChangeTab(obj)
        },

        //根据加工退料id查询加工退料基础信息
        getBasicData () {
            this.$Ajax
                .httpGet({
                    url: '/material/processingReturn/findById',
                    params: {
                        id: this.billid,
                    },
                })
                .then(res => {
                    this.basicFormData = res
                })
        },
        //根据加工退料id获取成品物资明细
        getMasterPlan () {
            this.$Ajax
                .httpGet({
                    url: '/material/processingReturn/getFinishedGoodsListById',
                    params: {
                        id: this.billid,
                    },
                })
                .then(res => {
                    res.forEach(item => {
                        item.materialClassName = item.topClassName
                        item.uuid = getUuid()
                        item.children.forEach(i => {
                            i.uuid = i.dtlId
                        })
                        const count = item.children.reduce(
                            (prev, c) => (prev += c.collectedQuantity || 0),
                            0
                        )
                        item.materialName = `小计： ${count.toFixed(4)}`
                    })
                    this.FinishedGoodsData = res
                })
        },
        //根据加工退料id获取原物资明细
        getRawMaterialsList () {
            this.$Ajax
                .httpGet({
                    url: '/material/processingReturn/getRawMaterialsListById',
                    params: {
                        id: this.billid,
                    },
                })
                .then(res => {
                    res.forEach(item => {
                        item.materialClassName = item.topClassName
                        item.uuid = getUuid()
                        item.children.forEach(i => {
                            i.uuid = i.dtlId
                        })
                        const count = item.children.reduce(
                            (prev, c) => (prev += c.collectedQuantity || 0),
                            0
                        )
                        item.materialName = `小计： ${count.toFixed(4)}`
                    })
                    this.materialsTableData = res
                })
        },
        //获取历史审核列表
        getAuditHistory () {
            const params = {
                billId: this.billid,
                billType: '1013',
                freeNextUnitIndex: 0,
                freeNextUser: '',
                isPass: true,
                isShareInAudit: true,
                opinion: '',
                orgId: '',
                orgName: '',
                userId: '',
                workId: ''
            }
            CommonApi.getAuditHistory(params).then(res => {
                this.auditHistoryTable = res
            })
        },
        //生成id
        getId () {
            this.$Ajax
                .httpGet({
                    url: '/uid/builder',
                    params: {
                        num: this.Uids ? this.Uids : 0,
                    },
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                }).then(res=>{
                    res.forEach(item=>{
                        this.UidArr.push(item)
                    })
                })
        },
        // 获取最后一个内容区域的高度，计算底部空白
        getLastConHeight () {
            let si = setInterval(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                if (document.getElementById('evaluateCon')) {
                    const lastConHeight =
            document.getElementById('evaluateCon').offsetHeight
                    console.log('lastConHeight: ', lastConHeight)
                    this.lastConHeight = lastConHeight
                    console.log('this.lastConHeight', this.lastConHeight)
                    clearInterval(si)
                    si = null
                }
            }, 100)
        },

        ctDelete () {
            this.clientPop(
                'info',
                '确定要删除吗？删除的数据可以在【回收站】还原或彻底删除。',
                this.delData
            )
        },
        //删除
        delData () {
            this.$Ajax
                .httpGet({
                    url: '/material/processingReturn/delete',
                    params: {
                        id: this.billid,
                    },
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                })
                .then(res => {
                    if (res.code == 200) {
                        this.clientPop('suc', '删除成功', this.cancel, null, this.cancel)
                    }
                })
        },

        handleFullScreen () {
            this.fullscreen = !this.fullscreen
        },
        //查询附件信息
        getAttach () {
            this.objFlag.flag5 = true
        },
        //关闭
        cancel () {
            this.dialogVisible = false
            this.$router.replace('./processReturn')
        },
        cellClsNm ({ column }) {
            if (column.label === '') {
                return 'fixed-left'
            }
        },
        cellMouseEnter (row) {
            this.MouseEnterId = row.dtlId
        },
        cellMouseLeave () {
            this.MouseEnterId = 0
        },
        onChangeTab (e) {
            const height  = $('#' + e.name).offset().top
            $.scrollTo(height - this.topHeight, 500)
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            this.clickTabFlag = true
            // 动画结束后，恢复状态
            setTimeout(() => {
                this.clickTabFlag = false
            }, 600)
        },
        count_ (obj) {
            return obj.children.reduce((prev, c) => (prev += c.amount || 0), 0)
        },
        //明细数据汇总方法
        uniqueArray (arr, key) {
            const map = new Map()
            return arr.filter(item => {
                const val = item[key] + '' || getUuid()
                return !map.has(val) && map.set(val, 1)
            })
        },

    },
}
</script>

<style lang="scss" scoped>
.buttons {
  left: 0;
}
.e-form {
  margin-bottom: 80px;
  padding: 0 20px;
  .tabs-title::before {
    content: "";
    height: 22px;
    width: 8px;
    border-radius: 40px;
    background-color: #2e61d7;
    display: block;
    position: absolute;
    left: 20px;
    margin-right: 20px;
  }
}

.e-table {
  background: #fff;
}
::v-deep.el-table .warning-row {
  display: none;
}

::v-deep .el-table__body-wrapper::-webkit-scrollbar {
  width: 6px; // 横向滚动条
  height: 10px; // 纵向滚动条
}
// 滚动条的滑块
::v-deep .el-table__body-wrapper::-webkit-scrollbar-thumb {
  background-color: #ddd;
  border-radius: 5px;
}

.el-tab-pane {
  margin-left: -10px;
}
.childTab {
  ::v-deep .el-tabs__header {
    position: absolute !important;
  }
  ::v-deep .el-tabs__content {
    padding: 0 0 0 20px !important;
  }
}
.childTab1 {
  ::v-deep .el-tabs__header {
    position: absolute !important;
    .el-tabs__nav-scroll {
      position: relative;
      .el-tabs__nav {
        position: fixed;
        top: 0;
        width: 190px;
      }
    }
  }
}
.childTab2 {
  ::v-deep .el-tabs__header {
    position: absolute !important;
    .el-tabs__nav-scroll {
      position: relative;
      .el-tabs__nav {
        position: absolute;
        bottom: 0;
        width: 100%;
      }
    }
  }
}
</style>